<template>
  <div id='departmentalStaff' class="views">
    <div class="pageHead">
      <el-button type="primary" round class="pull-right" size="medium" v-if="jurisdictionControl.J_AddStaff" @click="addStaff">添加</el-button>
    </div>
    <div class="pageMain">
      <el-col :span="5" style="height: 100%;">
        <div class="treeContent">
          <el-row class="treeHead">
            <el-col :span="12" class="treeHeadLeft">
              <span>部门</span>
            </el-col>
            <el-col :span="12" class="treeHeadRight">
              <span class="hoverToBlue" @click="treeoperation({departmentid: null, level: 0, rootid: null}, 'add')" v-if="jurisdictionControl.J_AddDep">添加</span>
              <span class="hoverToBlue blueColor" @click="isShowTreeOperation = !isShowTreeOperation" v-if="jurisdictionControl.J_AddDep || jurisdictionControl.J_EditDep || jurisdictionControl.J_DelDep">{{ isShowTreeOperation ? '完成' : '编辑' }}</span>
            </el-col>
          </el-row>
          <div class="treeMain">
            <el-tree :data="treeData" @node-click="treeNodeClick" :props="defaultProps" :render-content="renderContent" v-loading='treeLoading'></el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="19" style="height: 100%;">
        <div class="tableContent">
          <el-table border empty-text="部门职员" :data="tableData" style="width: 100%;" height="100%" v-loading='tableLoading' size='medium'>
            <el-table-column prop="userCode" label="编号" align="center"></el-table-column>
            <el-table-column prop="userName" label="用户名" align="center"></el-table-column>
            <el-table-column prop="realName" label="姓名" align="center"></el-table-column>
            <el-table-column prop="departmentName" label="所属部门" align="center"></el-table-column>
            <el-table-column prop="roleName" label="所属角色" align="center"></el-table-column>
            <el-table-column prop="lastLoginTime" label="最后登录时间" align="center" width="150px">
              <template slot-scope="scope">
                <span>{{scope.row.lastLoginTime}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" v-if="jurisdictionControl.J_EditStaff || jurisdictionControl.J_DelStaff">
              <template slot-scope="scope">
                <i class="iconfont" v-if="jurisdictionControl.J_EditStaff" @click="editStaff(scope.row)">&#xe606;</i>
                <i class="iconfont" v-if="jurisdictionControl.J_DelStaff" style="font-size: 17px;margin-left: 20px;" @click="delStaff(scope.row)">&#xe612;</i>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <pagination @getTableData="getTableData" :total="total" :listQuery="listQuery"></pagination>
      </el-col>
    </div>
    <!-- 删除弹框 -->
    <delPopup @delPostConfirm="delTreeNodePost" :delPopup="delPopup" />
    <!-- 新增修改部门弹框 -->
    <el-dialog :title="depTreeChangePopup.title" :visible.sync="depTreeChangePopup.isShow" width="380px" @closed="handleClose">
      <el-form :model="changeDepTreeParams" :rules="rules" ref="depForm" label-width="100px" style="padding: 40px 0;">
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="changeDepTreeParams.departmentName" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="departmentName">
          <el-select v-model="changeDepTreeParams.personId" filterable placeholder="请选择">
            <el-option v-for="item in userList" :key="item.userid" :label="item.userName" :value="item.userid">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="depTreeChangePopup.isShow = false" round>取 消</el-button>
        <el-button size="medium" type="primary" @click="changeDep" round :loading="isConfirmLoading">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mixinsMethod } from '@/util/util';
import { mapState } from 'vuex';
import delPopup from '@/components/delPopup';
import pagination from '@/components/pagination';
export default {
  name: 'departmentalStaff',
  components: {
    delPopup,
    pagination
  },
  data() {
    return {
      jurisdictionControl: {
        J_AddStaff: false, // 新增职员
        J_EditStaff: false, // 修改职员
        J_DelStaff: false, // 删除职员
        J_AddDep: false, // 新增部门
        J_EditDep: false, // 修改部门
        J_DelDep: false // 删除部门
      },
      defaultProps: {
        children: 'childrenList',
        label: 'departmentName'
      },
      treeLoading: false,
      tableLoading: false,
      tableData: [],
      total: 0,
      pagesNum: '',
      treeData: [],
      listQuery: {
        departmentid: '',
        PageIndex: 1, // 页码
        PageSize: 10 // 条数
      },
      isShowTreeOperation: false,
      delPopup: {
        title: '',
        isShow: false,
        describe: ''
      },
      changeDepTreeParams: {
        CompanyId: '',
        departmentName: '',
        ID: '',
        personId: '',
      },
      depTreeChangePopup: {
        title: '',
        isShow: false,
        type: ''
      },
      delDepParams: {
        CompanyId: '',
        BuMenId: ''
      },
      delStaffParams: {
        CompanyId: '',
        UserId: ''
      },
      isConfirmLoading: false, // 确认的loading
      delWhat: '',
      rownode: '',
      rules: {
        departmentName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.common.userInfo,
      moduleId: state => state.common.moduleId,
      userList: state => state.common.userList
    })
  },
  methods: {
    addStaff() {
      sessionStorage.removeItem('staffInfo');
      this.$router.push({ name: 'userView', query: { type: 'isAddJump', departmentid: this.listQuery.departmentid } });
    },
    editStaff(row) { // 修改职员信息
      this.$router.push({ name: 'userView', query: { type: 'isChangeJump' } });
      sessionStorage.setItem('staffInfo', JSON.stringify(row));
    },
    delStaff(row) {
      this.delWhat = 'staff';
      this.delStaffParams = {
        id: row.id,
        userid: row.userid
      };
      this.delPopup = {
        title: '删除职员',
        isShow: true,
        describe: '确定删除该职员吗？'
      };
    },
    handleClose() {
      this.clearObjVal(this.changeDepTreeParams);
    },
    changeDep() { // 修改部门名称
      this.$refs['depForm'].validate((valid) => {
        if (valid) {
          this.isConfirmLoading = true;
          switch (this.depTreeChangePopup.type) {
            case 'add':
              let params = {
                departmentName: this.changeDepTreeParams.departmentName,
                parentid: this.changeDepTreeParams.parentid,
                level: this.changeDepTreeParams.level,
                rootid: this.changeDepTreeParams.rootid,
                islast: true,
                personId: this.changeDepTreeParams.personId,
                subid: this.rownode.subid
              };
              this.$api.systemManagement.DepartmentEdit(params, 1).then(res => {
                if (res.data.status === 200) {
                  this.$notify({
                    title: '成功',
                    message: '新增下级部门成功',
                    type: 'success',
                    duration: 15001
                  });
                  this.depTreeChangePopup.isShow = false;
                  this.getTreeData();
                }
                setTimeout(() => { // 延迟开启确认
                  this.isConfirmLoading = false;
                }, 500);
              });
              break;
            case 'edit':
              let params1 = {
                ...this.changeDepTreeParams,
                subid: this.rownode.subid
              };
              this.$api.systemManagement.DepartmentEdit(params1, 2).then(res => {
                if (res.data.status === 200) {
                  this.$notify({
                    title: '成功',
                    message: '修改部门名称成功',
                    type: 'success',
                    duration: 1500
                  });
                  this.depTreeChangePopup.isShow = false;
                  this.getTreeData();
                }
                setTimeout(() => { // 延迟开启确认
                  this.isConfirmLoading = false;
                }, 500);
              });
              break;
            default:
              break;
          }
        } else {
          return false;
        }
      });
    },
    getTableData() { // 获取职员列表
      this.$api.systemManagement.GetUserPageList(this.listQuery).then(res => {
        let resList = res.data.data.items;
        this.tableData = resList;
        this.total = res.data.data.totalCount;
      });
    },
    cleardepTreeForm() {
      this.$nextTick(() => { // 清空表单验证
        if (this.$refs['depForm']) {
          this.$refs['depForm'].resetFields();
        }
      });
    },
    treeoperation(data, type) { // tree 操作
      event.stopPropagation();
      this.cleardepTreeForm();
      this.changeDepTreeParams = {
        departmentName: data.departmentName,
      };
      switch (type) {
        case 'add':
          this.changeDepTreeParams.departmentName = '';
          this.changeDepTreeParams.level = data.level + 1;
          this.changeDepTreeParams.rootid = data.rootid;
          this.changeDepTreeParams.parentid = data.departmentid;
          this.depTreeChangePopup = {
            title: '部门添加',
            isShow: true,
            type: 'add'
          };
          break;
        case 'edit':
          this.changeDepTreeParams.id = data.id;
          this.changeDepTreeParams.departmentid = data.departmentid;
          this.depTreeChangePopup = {
            title: '部门修改',
            isShow: true,
            type: 'edit'
          };
          break;
        default:
          this.delTreeNode(data);
          break;
      }
    },
    delTreeNodePost() { // tree 删除部门的请求
      if (this.delWhat === 'tree') {
        let params = {
          ...this.delDepParams,
          subid: this.rownode.subid
        };
        this.$api.systemManagement.DepartmentEdit(params, 3).then(res => {
          if (res.data.status === 200) {
            this.$message({ message: '删除成功', type: 'success' });
          }
          this.delPopup.isShow = false;
          this.getTreeData();
        });
      } else if (this.delWhat === 'staff') {
        this.$api.systemManagement.UserEdit(this.delStaffParams, 3).then(res => {
          if (res.data.status === 200) {
            this.$message({ message: '删除成功', type: 'success' });
          }
          this.delPopup.isShow = false;
          this.getTableData();
        });
      }
    },
    delTreeNode(data) { // tree 删除部门的弹框和参数
      this.delWhat = 'tree';
      this.delDepParams = {
        id: data.id,
        departmentid: data.departmentid
      };
      this.delPopup = {
        title: '删除部门',
        isShow: true,
        describe: '确定删除该部门吗？'
      };
    },
    getTreeData() {
      this.treeLoading = true;
      let params = {
        subid: this.userInfo.subid
      };
      this.$api.systemManagement.GetDepartmentTree(params).then(res => {
        let resData = res.data.data;
        this.mapTreeData(resData);
        this.treeData = resData;
        this.treeLoading = false;
      });
    },
    treeNodeClick(node) { // 树状结构点击 departmentid
      this.listQuery.departmentid = node.departmentid;
      this.listQuery.PageIndex = 1; // 搜索把页数重置为1
      this.rownode = node;
      this.getTableData();
    },
    renderContent(h, { node, data }) { // 自定义tree节点
      return (
        <span class="custom-tree-node">
          <img width="15px" src={data.icons} />
          <span style="margin-left:5px;">{node.label}</span>
          <div class="pull-right" v-show={this.isShowTreeOperation}>
            <i class="iconfont" v-show={this.jurisdictionControl.J_AddDep} on-click={() => this.treeoperation(data, 'add')}>&#xe6ac;</i>
            <i class="iconfont" v-show={this.jurisdictionControl.J_EditDep} on-click={() => this.treeoperation(data, 'edit')}>&#xe617;</i>
            <i class="iconfont" v-show={this.jurisdictionControl.J_DelDep} on-click={() => this.treeoperation(data, 'del')}>&#xe612;</i>
          </div>
        </span>
      );
    },
    getJurisdiction() {
      if (this.userInfo.isadmin) {
        this.jurisdictionControl = {
          J_AddStaff: true, // 新增职员
          J_EditStaff: true, // 修改职员
          J_DelStaff: true, // 删除职员
          J_AddDep: true, // 新增部门
          J_EditDep: true, // 修改部门
          J_DelDep: true // 删除部门
        };
        return;
      }
      let params = {
        id: this.moduleId
      };
      this.$api.publicApi.GetActionInfo(params).then(res => {
        let resData = res.data.data;
        resData.map(item => {
          if (item.name === '添加部门') {
            this.jurisdictionControl.J_AddDep = true;
          }
          if (item.name === '修改部门') {
            this.jurisdictionControl.J_EditDep = true;
          }
          if (item.name === '删除部门') {
            this.jurisdictionControl.J_DelDep = true;
          }
          if (item.name === '添加职员') {
            this.jurisdictionControl.J_AddStaff = true;
          }
          if (item.name === '修改职员') {
            this.jurisdictionControl.J_EditStaff = true;
          }
          if (item.name === '删除职员') {
            this.jurisdictionControl.J_DelStaff = true;
          }
        });
      });
    }
  },
  created() {
  },
  mounted() {
    this.getJurisdiction();
    this.getTreeData();
    this.getTableData();
  },
  activated() {
    if (this.$route.query.ischange == true) {
      this.getTableData();
    }
  },
  mixins: [mixinsMethod]
};
</script>
<style lang='less'>
#departmentalStaff {
  .el-form {
    .el-input__inner {
      width: auto;
    }
  }
  .treeContent {
    border: 1px solid #e7ebf5;
    height: 100%;
    font-size: 14px;
    .treeHead {
      background: #f7f8fc;
      height: 50px;
      line-height: 50px;
      padding: 0 20px;
      .treeHeadLeft {
        color: #333333;
      }
      .treeHeadRight {
        color: #87888c;
        text-align: right;
        span {
          &:last-child {
            margin-left: 20px;
          }
        }
      }
    }
    .treeMain {
      padding: 8px 0 0 8px;
      height: calc(100% - 60px);
      overflow: auto;
      .el-tree-node {
        &:hover .iconfont {
          color: #606266;
        }
      }
      .custom-tree-node {
        display: block;
        width: 100%;
        padding-right: 15px;
        .iconfont {
          font-size: 16px;
          margin-left: 15px;
          &:hover {
            color: #5c8ffc;
          }
        }
      }
    }
  }
  .el-table {
    thead {
      th {
        height: 50px;
        color: #87888c;
        background: #f7f8fc;
        font-size: 14px;
      }
    }
    tbody {
      td {
        // border-bottom: none;
        .iconfont {
          color: #999;
          &:hover {
            color: #39a4ed;
            cursor: pointer;
          }
        }
      }
    }
    .is-scrolling-none {
      height: 85%;
    }
  }
  .pageMain {
    .el-col-5 {
      width: 23% !important;
    }
    .el-col-19 {
      width: 76% !important;
    }
  }
}
</style>
